import random
import tkinter
import Team
import Trat
import os
import Generator_Jazdci

class Sezona():
    def __init__(self, canvas, hrac_team=None, dlzka=0, nova_sezona=False, obtiaznost=1):
        #zakladne info o sezone
        self.canvas = canvas
        self.podujatie = 1
        self.faza_preteku = 1
        self.dlzka = dlzka
        self.hrac_team = hrac_team

        #hrac a ostatne teamy
        self.teamy = []
        self.clanky = []

        #nacita detaily novej sezony ako teamy, clanky, ...
        if(nova_sezona):
            Generator_Jazdci.generator(True)
            self.nova_sezona(obtiaznost)
            self.trate = self.nacitaj_trate()

        #info k preteku
        self.pocet_vypadnutych = 0
        self.kolo = 0
        self.max_kolo = [35,30,25,15,65]

    def info(self):
        print("manazer = ", self.hrac_team.manazer.meno)
        print("team = ", self.hrac_team.meno_teamu)
        print("dlzka = ", self.dlzka)

    def nastav_fazu_preteku_jazdcom(self):
        print("> Nastavujem fazu ...")
        je_trening = self.faza_preteku in range(1,4)
        for jazdec in self.jazdci:
            jazdec.faza_preteku = self.faza_preteku
            jazdec.je_trening = je_trening
            if(je_trening):
                #print("Je trening")
                jazdec.nastav_auto_pred_treningom()

    def dalsia_faza(self):
        self.kolo = 0
        self.faza_preteku += 1
        self.nastav_fazu_preteku_jazdcom()
        if(self.faza_preteku == 6):
            self.body_jazdci()
            self.dalsi_pretek()
        for team in self.teamy + [self.hrac_team]:
            team.zisti_body()
            

    def dalsi_pretek(self):
        self.kolo = 0
        self.faza_preteku = 1
        self.nastav_fazu_preteku_jazdcom()
        self.podujatie += 1

    def ulozit(self, subor):
        #print(subor)
        text_subor = open(subor, "w")

        #zakladne informacie
        text_subor.write("zakladne_info={};{}\n".format(self.hrac_team.manazer.meno, self.hrac_team.meno_teamu))
        text_subor.write("prazdny_slot=False\n")

        
        #info o sezone
        text_subor.write("podujatie={}\n".format(self.podujatie))
        text_subor.write("faza_preteku={}\n".format(self.faza_preteku))
        text_subor.write("dlzka={}\n".format(self.dlzka))
        text_subor.write("hrac_team={}\n".format(self.hrac_team.ulozit()))
        for team in self.teamy:
            text_subor.write("team={}\n".format(team.ulozit()))

        text_subor.close()

    def nacitat(self, subor):
        text_subor = open(subor, "r")

        for riadok in text_subor:
            atribut, hodnota = riadok.strip().split("=")
            if(atribut == "podujatie"):
                self.podujatie = int(hodnota)
            if(atribut == "faza_preteku"):
                self.faza_preteku = int(hodnota)
            if(atribut == "dlzka"):
                self.dlzka = int(hodnota)
            if(atribut == "hrac_team"):
                self.hrac_team = Team.Team(self.canvas).nacitat(hodnota)
                for jazdec in self.hrac_team.jazdci:
                    jazdec.AI = False
            if(atribut == "team"):
                self.teamy += [Team.Team(self.canvas).nacitat(hodnota)]

        self.trate = self.nacitaj_trate()
        #naplni jazdcov
        self.napln_jazdcov()
        self.nastav_fazu_preteku_jazdcom()
        text_subor.close()

        return self

    def napln_jazdcov(self):
        self.jazdci = []
        for team in [self.hrac_team] + self.teamy:
            self.jazdci += team.jazdci
        print("> Bolo naplnenych ", len(self.jazdci), " jazdcov ...")
        

    def nova_sezona(self, obtiaznost):
        self.faza_preteku = 1
        self.teamy = self.vytvor_nove_teamy(obtiaznost)
        self.napln_jazdcov()
        self.nastav_fazu_preteku_jazdcom()
        #print(self.teamy)
        self.clanky = self.vytvor_nove_clanky()

    def nacitaj_trate(self):
        trate = []
        dirname = os.path.dirname(__file__)
        filename = os.path.join(dirname, "data/trate")
        for file in os.listdir(filename):
            if file.endswith(".txt"):
                print("> Nahravam trat: ", str(file), "...")
                meno_trate = os.path.join(filename, file)
                trate += [Trat.Trat(meno_trate)]

        #print("- - - - - -")
        return trate

    def vytvor_nove_teamy(self, obtiaznost):
        print("> Vatvaram nove teamy ...")
        jazdci = []
        teamy = []
        pouziti_jazdci = []
        meno_teamov = ["Green Bulls Racing", "Ferorri", "MatFyz Racing", "Mircedes",
                       "Sahara Racing", "Trump Formula Team", "UK racing Team", "Jaros Team",
                       "Python Formula Team"]
        random.shuffle(meno_teamov)
        
        meno_manazerov = ["Patrick Gerrard", "Marek Jaros", "Isaac Blaho", "Martin Russel",
                          "Andrey Ovechkin", "Ali Al Bashad", "Imrei Gyurcsi", "Kim Cho-Li",
                          "Brandon Hartley"]
        random.shuffle(meno_manazerov)
        
        text_subor = open("data/jazdci.txt", "r")
        for riadok in text_subor:
            jazdci += [Team.Jazdec(self.canvas).nacitat(riadok)]
        text_subor.close()

        jazdci.sort(key= lambda x: x.level)

        for level in range(1,18,2):
            jazdec_1 = random.choice(jazdci[5*level:])
            jazdec_2 = random.choice(jazdci[5*level:])
            jazdci.remove(jazdec_1); jazdci.remove(jazdec_2)
                
            meno_teamu = meno_teamov.pop(0)
            meno_manazera = meno_manazerov.pop(0)
            followeri = random.randint(25000, 100000) * level
            peniaze = random.randint(100000000, 1000000000)

            teamy += [Team.Team(self.canvas).set_up(meno_teamu, meno_manazera, followeri, peniaze, [jazdec_1, jazdec_2])]

        jazdci = list(set(jazdci) - set(pouziti_jazdci))
        jazdci.sort(key= lambda x: x.level)
        self.prirad_jazdcov_k_hracovmu_teamu(jazdci, obtiaznost)

        self.jazdci = []
        for team in [self.hrac_team] + self.teamy:
            self.jazdci += team.jazdci

        return teamy

    def prirad_jazdcov_k_hracovmu_teamu(self, jazdci, obtiaznost):
        #jazdci level 5 a nizsie, zamiesa ich nahodne
        index = 30 - obtiaznost * 5
        jazdci = jazdci[:index]
        random.shuffle(jazdci)
        #vyberie jazdcov a priradi teamu hraca
        jazdec_1 = jazdci.pop(0); jazdec_2 = jazdci.pop(0)
        jazdec_1.AI = False; jazdec_2.AI = False
        jazdec_1.team = self.hrac_team; jazdec_2.team = self.hrac_team
        jazdec_1.nastav_auto(self.hrac_team); jazdec_2.nastav_auto(self.hrac_team)
        jazdec_1.obr_c["oblecenie"] = self.hrac_team.manazer.obr_c["oblecenie"]
        jazdec_2.obr_c["oblecenie"] = self.hrac_team.manazer.obr_c["oblecenie"]
        self.hrac_team.jazdci += [jazdec_1, jazdec_2]

    def vykresli_sezona_info(self, x, y):
        #obrazok manazera
        self.hrac_team.manazer.vykresli(x, y+25, 7)
        #mena
        self.canvas.create_text(x + 100, y + 15, font="Ariel 13", text=self.hrac_team.manazer.meno)
        self.canvas.create_text(x + 100, y + 30, font="Ariel 13", text=self.hrac_team.meno_teamu)
        self.canvas.create_line(x + 180, y, x + 180, y + 50, width=2)
        self.canvas.create_text(x + 260, y + 15, font="Ariel 13", text="{:,} €".format(self.hrac_team.peniaze))
        self.canvas.create_text(x + 260, y + 30, font="Ariel 13", text="Podujatie: {}/{}".format(self.podujatie, self.dlzka))

    def vykresli_poradie_jazdcov_najlepsie_kolo(self, x, y):
        #utriedenie podla NAJLEPSIEHO KOLA
        self.jazdci.sort(key= lambda x: x.najlepsie_kolo)

        #ak je poziacia nastavena na -1, vsetkym da aktualnu poziciu
        if(self.jazdci[0].pozicia == -1):
            for p, jazdec in enumerate(self.jazdci):
                jazdec.update_pozicia(p+1)

                
        #kreslenie
        farba_1, farba_2 = farba_1, farba_2 = "#e2e2e2", "#c7c7c7"
        for i, jazdec in enumerate(self.jazdci):
            farba = farba_1
            farba_pozicia = "black"
            if(jazdec.team.meno_teamu == self.hrac_team.meno_teamu):
                farba = "#c3c968"
            if(jazdec.pozicia < i+1):
                farba_pozicia = "red"
            if(jazdec.pozicia > i+1):
                farba_pozicia = "green"
            if(jazdec.najlepsie_kolo != -1): jazdec.update_pozicia(i+1)
            self.canvas.create_rectangle(x, y + i*28, x + 430, y + (i+1)*28, fill=farba)
            self.canvas.create_text(x + 13, y + 14 + i*28, text="{:2}.".format(jazdec.pozicia), font="Ariel 12 bold", fill=farba_pozicia)
            self.canvas.create_text(x + 105, y + 14 + i*28, text=jazdec.meno, font="Ariel 12 bold", fill=farba_pozicia)
            self.canvas.create_text(x + 255, y + 14 + i*28, text=jazdec.team.meno_teamu, font="Ariel 12")
            self.canvas.create_text(x + 390, y + 14 + i*28, text=jazdec.cas(jazdec.najlepsie_kolo), font="Ariel 12")
            farba_1, farba_2 = farba_2, farba_1
        self.canvas.create_rectangle(x, y, x + 430, y + 560, width=2)

    def vykresli_poradie_jazdcov_najlepsi_cas(self, x, y):
        #utriedenie podla CELKOVEHO CASU
        self.jazdci.sort(key= lambda x: x.celkovy_cas)

        #najlepsi cas
        najlepsi_cas = self.jazdci[0].celkovy_cas

        #ak je poziacia nastavena na -1, vsetkym da aktualnu poziciu
        if(self.jazdci[0].pozicia == -1):
            for p, jazdec in enumerate(self.jazdci):
                jazdec.update_pozicia(p+1)
        
        #kreslenie
        farba_1, farba_2 = farba_1, farba_2 = "#e2e2e2", "#c7c7c7"
        for i, jazdec in enumerate(self.jazdci):
            farba = farba_1
            farba_pozicia = "black"
            if(jazdec.team.meno_teamu == self.hrac_team.meno_teamu):
                farba = "#c3c968"
            if(jazdec.pozicia < i+1):
                farba_pozicia = "red"
            if(jazdec.pozicia > i+1):
                farba_pozicia = "green"
            if(jazdec.celkovy_cas != -1): jazdec.update_pozicia(i+1)
            self.canvas.create_rectangle(x, y + i*28, x + 430, y + (i+1)*28, fill=farba)
            self.canvas.create_text(x + 13, y + 14 + i*28, text="{:2}.".format(jazdec.pozicia), font="Ariel 12 bold", fill=farba_pozicia)
            self.canvas.create_text(x + 105, y + 14 + i*28, text=jazdec.meno, font="Ariel 12 bold", fill=farba_pozicia)
            self.canvas.create_text(x + 255, y + 14 + i*28, text=jazdec.team.meno_teamu, font="Ariel 12")
            self.canvas.create_text(x + 390, y + 14 + i*28, text="+ " + jazdec.cas(jazdec.celkovy_cas - najlepsi_cas), font="Ariel 12")    
            farba_1, farba_2 = farba_2, farba_1
        self.canvas.create_rectangle(x, y, x + 430, y + 560, width=2)       

    def reset_jazdci(self, typ):
        teamy = [self.hrac_team] + self.teamy
        for team in teamy:
            for jazdec in team.jazdci:
                if(typ == "preteky"):
                    jazdec.reset_preteky()
                if(typ == "faza"):
                    jazdec.reset_faza()

    def kvalifikacia(self, kolo):
        for jazdec in self.jazdci:
            jazdec.kvalifikacny_rezim(kolo)

    def jazda(self, pretek, kolo):
        print(6 * "-----" + "> Kolo:", kolo, "<-----")
        trat = self.trate[self.podujatie - 1]
        for jazdec in self.jazdci:
            if(jazdec not in self.hrac_team.jazdci):
                jazdec.auto.pritlak = 1
            if(not jazdec.porucha):
                cas = trat.prejdi_kolo(jazdec, pretek, kolo)
                if(cas != -1):
                    jazdec.update_kolo(cas)
                else:
                    jazdec.update_kolo(-1)

    def strategia(self):
        print("> Pocitam strategie ...")
        trat = self.trate[self.podujatie - 1]
        self.vykresli_simulacia_okno("Placeholder", 15)
        for i, jazdec in enumerate(self.jazdci):
            if(jazdec in self.hrac_team.jazdci):
                continue
            
            jazdec.strategia(trat)

    def vykresli_simulacia_okno(self, meno, pocet):
        self.canvas.delete("all")
        #info
        self.canvas.create_text(640, 250, font="Ariel 20 bold", text="Prebieha simulacia strategii ...")
        self.canvas.create_text(640, 280, font="Ariel 15", text="Simulujem jazdca: {}".format(meno))
        #bar
        self.canvas.create_rectangle(340, 320, pocet * 30, 350, fill="red")
        self.canvas.create_rectangle(340, 320, 940, 350, width=3, outline="black")
        self.canvas.create_text(640, 335, font="Ariel 15 bold", text="{}%".format(5*pocet))
         
    def vykresli_poradie_jazdcov(self, x, y, pocet):
        self.jazdci.sort(key= lambda x: x.body, reverse=True)

        #kreslenie
        self.canvas.create_text(x + 140, y - 20, text="TOP {} jazdcov v sampionate".format(pocet), font="Ariel 15 bold")
        farba_1, farba_2 = "#e2e2e2", "#c7c7c7"
        i = 0
        while(i < pocet):
            farba = farba_1
            if(self.jazdci[i].team.meno_teamu == self.hrac_team.meno_teamu):
                farba = "#c3c968"
            self.canvas.create_rectangle(x, y + i*28, x + 380, y + (i+1)*28, fill=farba)
            self.canvas.create_text(x + 15, y + 14 + i*28, text="{:2}.".format(i+1), font="Ariel 12 bold")
            self.canvas.create_text(x + 95, y + 14 + i*28, text=self.jazdci[i].meno, font="Ariel 12 bold")
            self.canvas.create_text(x + 250, y + 14 + i*28, text=self.jazdci[i].team.meno_teamu, font="Ariel 12")
            self.canvas.create_text(x + 360, y + 14 + i*28, text=str(self.jazdci[i].body), font="Ariel 12")
            i += 1
            farba_1, farba_2 = farba_2, farba_1
        self.canvas.create_rectangle(x, y, x + 380, y + pocet*28, width=2)

    def vykresli_poradie_tymov(self,x, y, pocet):
        teamy = self.teamy + [self.hrac_team]
        for team in teamy:
            team.zisti_body()
        teamy.sort(key= lambda x: x.body, reverse=True)

        #kreslenie
        self.canvas.create_text(x + 140, y - 20, text="Poradie v sampionate teamov", font="Ariel 15 bold")
        farba_1, farba_2 = "#e2e2e2", "#c7c7c7"
        i = 0
        while(i < pocet):
            farba = farba_1
            if(teamy[i] == self.hrac_team):
                farba = "#c3c968"
            self.canvas.create_rectangle(x, y + i*28, x + 380, y + (i+1)*28, fill=farba)
            self.canvas.create_text(x + 15, y + 14 + i*28, text="{:2}.".format(i+1), font="Ariel 12 bold")
            self.canvas.create_text(x + 190, y + 14 + i*28, text=teamy[i].meno_teamu, font="Ariel 12 bold")
            self.canvas.create_text(x + 360, y + 14 + i*28, text=str(teamy[i].body), font="Ariel 12")
            i += 1
            farba_1, farba_2 = farba_2, farba_1
        self.canvas.create_rectangle(x, y, x + 380, y + pocet*28, width=2)

    def body_jazdci(self):
        body = [25,18,15,13,10,8,6,4,2,1]
        self.jazdci.sort(key=lambda x: x.pozicia)
        for i in range(10):
            if(not self.jazdci[i].porucha):
                self.jazdci[i].body += body[i]

        #umiestnenia
        for i, jazdec in enumerate(self.jazdci):
            jazdec.umiestnenia += [i+1]

            

    def skusenosti_jazdci(self, typ):
        self.jazdci.sort(key=lambda x: x.pozicia)
        
        if(typ == "trening"):
            skusenosti = 10
        if(typ == "kvalifikacia"):
            skusenosti = 20
        if(typ == "pretek"):
            skusenosti = 30
            
        for jazdec in self.jazdci:
            #print(jazdec.meno)
            jazdec.skusenosti += skusenosti
            skusenosti -= 1
            if(skusenosti == 0): skusenosti = 1

    def TEST_vykresli_jazdci(self):
        for stlpec in range(3):
            for rad in range(3):
                self.teamy[stlpec * 3 + rad].vykresli_info_o_jazdcoch(10 + stlpec * 380, 10 + rad * 290)
            

            
    def vytvor_nove_clanky(self):
        return []
        
